package com.winning.devops.batch.parameter.config;

import com.winning.devops.batch.parameter.listener.ParameterStepListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * job 参数
 *
 * @author chensj
 * @date 2020-02-29 19:48
 */
@Configuration
public class ParametersDemoConfig {

    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(ParametersDemoConfig.class);

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;


    @Bean
    public Job parameterJob() {
        return jobBuilderFactory
                .get("parameterJob")
                .start(parameterDemoStep1())
                .build();
    }

    /**
     * job 执行的是step，Job使用的数据肯定是在step中使用
     * 那么就是给step传递参数即可
     * <p>
     * 如何给step传递参数
     * <p>
     * 通过listener(Step级别的监听器)传递参数
     *
     * @return step
     */
    @Bean
    public Step parameterDemoStep1() {
        return stepBuilderFactory
                .get("parameterDemoStep1")
                .listener(new ParameterStepListener())
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                        Map<String, Object> jobParameters = chunkContext.getStepContext().getJobParameters();
                        logger.info("检查[{}]是否存在参数：{}", chunkContext.getStepContext().getStepName(),
                                !jobParameters.isEmpty());
                        if (!jobParameters.isEmpty()) {
                            for (String key : jobParameters.keySet()) {
                                logger.info("key : {} value : {}", key, jobParameters.get(key));
                            }
                        } else {
                            logger.info("{} 中 无参数", chunkContext.getStepContext().getStepName());
                        }

                        return RepeatStatus.FINISHED;
                    }
                }).build();
    }

}
